<?php

require_once 'User.php';

class Models_Auth {
	
	/**
	 * 
	 * Authenticate the user, using the supplied username and password
	 * After authenticating successfully, the user credentials will be stored
	 * in the current session, so that he don't have to supply username and 
	 * password anymore
	 * @param $username
	 * @param $passwd
	 */
	public static function AuthenticateUser($username, $passwd) {
		if (!is_string($username) || !is_string($passwd))
			return false;
		$user = new User ( null );
		$passwd = Utils::EncryptedPassword($passwd);
		$stmt = $user->select ()->where ( 'username = :_username and password = :_password' )->bind ( array (':_username' => $username, ':_password' => $passwd ) );
		$result = $user->fetchRow ( $stmt );
		
		if (is_null ( $result )) {
			return false;
		}
		
		$session = new LikeMVC_Session_Behaviour_Namespace ( null, "user" );
		$session->set ( 'auth', 'ok' );
		$session->set ( 'userid', $result->id );
		
		return true;
	}
	
	/**
	 * Test if the current user is authenticated
	 */
	public static function IsUserAuthenticated()	{
		$session = new LikeMVC_Session_Behaviour_Namespace ( null, "user" );
		$result = $session->get ( 'auth' );
		if ($result == 'ok')	{
			return true;
		}
		return false;
	}
}

?>